// Node-RED Function Node Code - 使用global context在整个Node-RED实例中共享数据
// 用于保存MQTT实时数据的结构化存储

// 初始化全局数据存储
if (!global.get('mqttDataStore')) {
    global.set('mqttDataStore', {});
}

// 从topic中提取tenantId和projectId
function extractIdsFromTopic(topic) {
    const parts = topic.split('/');
    if (parts.length >= 6) {
        return {
            tenantId: parts[4],
            projectId: parts[5]
        };
    }
    return null;
}

// 保存数据到结构化存储
function saveDataToStore(tenantId, projectId, payload) {
    const dataStore = global.get('mqttDataStore') || {};
    
    // 确保层级结构存在
    if (!dataStore[tenantId]) {
        dataStore[tenantId] = {};
    }
    if (!dataStore[tenantId][projectId]) {
        dataStore[tenantId][projectId] = {};
    }
    
    // 保存每个propId和对应的val
    for (const [propId, val] of Object.entries(payload)) {
        dataStore[tenantId][projectId][propId] = {
            value: val,
            timestamp: new Date().toISOString(),
            lastUpdate: Date.now()
        };
    }
    
    // 保存回global context
    global.set('mqttDataStore', dataStore);
    
    return dataStore[tenantId][projectId];
}

// 主处理逻辑
try {
    // 获取topic和payload
    const topic = msg.topic;
    const payload = msg.payload;
    
    // 验证数据格式
    if (!topic || !payload || typeof payload !== 'object') {
        node.error('Invalid message format: topic or payload missing/invalid');
        return null;
    }
    
    // 从topic中提取ID
    const ids = extractIdsFromTopic(topic);
    if (!ids) {
        node.error('Invalid topic format: cannot extract tenantId and projectId');
        return null;
    }
    
    const { tenantId, projectId } = ids;
    
    // 保存数据
    const savedData = saveDataToStore(tenantId, projectId, payload);
    
    // 创建返回消息
    msg.result = {
        topic: topic,
        tenantId: tenantId,
        projectId: projectId,
        savedData: savedData,
        timestamp: new Date().toISOString(),
        messageCount: Object.keys(payload).length
    };
    
    // 输出保存结果
    node.log(`Data saved for tenant: ${tenantId}, project: ${projectId}, props: ${Object.keys(payload).length}`);
    
    return msg;
    
} catch (error) {
    node.error('Error processing MQTT data: ' + error.message);
    return null;
}
